<?php


namespace api\applets\controller;


use cmf\controller\RestBaseController;
use think\App;
use think\Db;
use think\Exception;
use WxPayUnifiedOrder;

class ServiceController extends RestBaseController
{
    private $appid = "wxd5861ea6d3afeef2";
    private $mch_id = "1538352981";
    private $KEY = 'zhihuimuyuanZHIHUIMUYUAN20200814';

//    public function __construct()
//    {
//        $this->appid = 'wxd5861ea6d3afeef2';
//        $this->mch_id = '1538352981';
//        $this->KEY = 'zhihuimuyuanZHIHUIMUYUAN20200814';
//    }
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
//    vendor("WxPay.lib.WxPay#Data");
        require_once dirname(dirname(__DIR__)) . '/applets/Wxpay/lib/WxPay.Data.php';
        require_once dirname(dirname(__DIR__)) . '/applets/Wxpay/lib/WxPay.Api.php';
        require_once dirname(dirname(__DIR__)) . '/applets/Wxpay/lib/WxPay.Notify.php';
        //vendor("WxPay.lib.WxPay#Config");
//    vendor("WxPay.lib.WxPay#Notify");
//    Vendor("WxPay.lib.WxPay#Api");
    }

    /**
     * 维保查询
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function maintenanceQuery()
    {
        try {
            $request = $this->request;
            $tomb_id = $request->param("tomb_id");
            $customer_id = $request->param("customer_id");
            $data = Db::name("service_weibao")->alias("w")
                ->field("w.id,w.type,w.confirm_content,w.service_status")
//                ->join("maintenance_project m", "m.wb_id = w.id", "left")
                ->where(array("w.tomb_id" => $tomb_id, "w.customer_id" => $customer_id, "w.pay_status" => 1))
                ->order("w.add_time", "desc")
                ->find();
            $name = "";
            if ($data['type'] == 1 || $data['type'] == 2) {
                $part_name = Db::name("maintenance_project")->field("part_name")->where(['wb_id' => $data['id']])->select();
                for ($i = 0; $i < count($part_name); $i++) {
                    $name .= $part_name[$i]['part_name'] . ',';
                }
                $name = substr($name, 0, strlen($name) - 1);
            } else {
                $part_name = Db::name("maintenance_project")->field("part_name")->where(['wb_id' => $data['id']])->find();
                $name = $part_name['part_name'];
            }
            $data['part_name'] = $name;
            $img = Db::name("service_confirm")->field("url,weibao_type")->where("service_id", $data["id"])->select();
            $data['img'] = $img;
            $this->success("请求成功！", $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 满意确认
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function confirm()
    {
        $id = $this->request->param("wb_id");
        $flag = Db::name("service_weibao")->where("id", $id)->update(["service_status" => 3]);
        if ($flag == 1) {
            $this->success("确认成功！", $flag);
        } else {
            $this->error("确认失败，请不要重复确认！", $flag);
        }
    }

    /**
     * 查询墓编号
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTombNumber()
    {
        $request = $this->request;
        $openId = $request->param("openID");
        $data = Db::name("order")->alias("o")->distinct(true)
            ->field("info.tomb_number,co.colID tomb_id,info.id customer_id")
            ->join("customer_info info", "o.customer_id = info.id", "left")
            ->join("tombarea_row_col co", "o.tomb_id = co.colID", "left")
            ->join("archives_deceased ad", "o.order_id = ad.order_id", "left")
            ->join("tombarea_information_product p", "co.colID = p.tomb_id", "left")
            ->where(array("o.openID" => $openId, "info.is_dy_mz" => 1))
            ->select();
        $this->success("请求成功！", $data);
    }

    public function wx_pay()
    {
        //查询用户的openid
        $post = $this->request->param();
        $openid = $post["openId"];

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("bks");
        $input->SetAttach("bks");
        $input->SetOut_trade_no($this->getRand(20, true));
        $input->SetTotal_fee($post['total_amount'] * 100);
        $input->SetTime_start(date("YmdHis"));//开始时间
        $input->SetTime_expire(date("YmdHis", time() + 3600));//有效时间
        $input->SetGoods_tag("buy");
        $input->SetNotify_url('https://mall.youzainet.com/index.php/Api/Pay/wxlista');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //$this->returnMsg("T",$order);
//        print_r($order);die;
        $arr = array();
        $arr['appId'] = $order['appid'];
        $arr['nonceStr'] = $order['nonce_str'];
        $arr['package'] = "prepay_id=" . $order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = $this->ToUrlParams($arr);
        $jmstr = $str . "&key=" . \WxPayConfig::KEY;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        //echo json_encode(array('status'=>1,'arr'=>$arr));
        //exit();
        $this->success("T", $arr);
    }

    /**
     * 更新数据
     */
    public function updateMaintenanceFee()
    {
        try {
            $request = $this->request;
            $tomb_id = $request->param("tomb_id");
            $customer_id = $request->param("customer_id");
//            $total_fee = $request->param("total_fee");
            $total_price = $request->param("total_price");
            $phone = $request->param("phone");
            $duration = $request->param("duration");
            $manager_price = $request->param("manager_price");
            $openId = $request->param("openId");
            $flag = $request->param("flag");
            if ($flag == 1) {
                $data = Db::name("order")->field("order_id,whq_end_date")->where(array("tomb_id" => $tomb_id, "customer_id" => $customer_id, "openId" => $openId))->order("add_time", "desc")->find();
//                echo Db::name("protect_payment")->getLastSql();
//                print_r($data);die;
                $post = [
                    'manager_price' => $manager_price,
                    'duration' => $duration,
                    'total_price' => $total_price,
                    'phone' => $phone,
                    'pay_time' => time(),
                    'create_time' => time(),
                    'mw_id' => $tomb_id,
                    'pay_status' => 1,
                    'customer_id' => $customer_id,
                    'order_id' => $data['order_id'],
                    'end_time' => intval($data['whq_end_date']) + $duration * 3600 * 24 * 365,
//                    'total_fee' => $total_fee,
                ];

//                if (!empty($data)){
//                    $post['end_time'] = intval($data['whq_end_date']) + $duration * 3600 * 24 * 365;
//                }
                // 插入财务表
                $tomb = Db::name("tombarea_row_col")->field("num")->where("colID", $tomb_id)->find();
                $pay_ins = [
                    'type' => 3,
                    'itype' => 2,
                    'pay_sn' => 'JS' . date('YmdHi'),//订单编号
                    'tomb_id' => $tomb_id,
                    'tomb_num' => $tomb['num'],
                    'tom_price' => 0,//购墓价格
                    'discount_rate' => 0,//折扣
                    'deal_price' => $total_price,//成交
                    'total_price' => $total_price,//应收金额
                    'add_time' => time(),//备注
                    'handle' => cmf_get_current_admin_id(),//收款人
                    'pay_real_name' => cmf_get_current_admin_id(),//收款人
                    'status' => 0,// 付款方式
//            'other_id'=> $form_id,
                    'customer_id' => $customer_id,
                ];
                $pay = Db::name("order_pay_log")->insertGetId($pay_ins);
                $post['pay_id'] = $pay;
                $res = Db::name("protect_payment")->insert($post);
                Db::name("order")->where(array("tomb_id" => $tomb_id, "customer_id" => $customer_id, "openId" => $openId))->update(['whq_end_date' => intval($data['whq_end_date']) + $duration * 3600 * 24 * 365]);
                if ($res == 1) {
                    $this->success("成功", $res);
                } else {
                    $this->error('失败');
                }

            } else {
                $this->error("支付失败！");
            }

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * 缴纳维护费支付
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function payMaintenanceFee()
    {
        $post = @file_get_contents('php://input');
        $post = json_decode($post, true);
        print_r($post['param']);
        $protectPayment = Db::name("protect_payment")->field("end_time")->where(array("mw_id" => $post['param']['tomb_id'], "customer_id" => $post['param']['customer_id']))->order("pay_time", "desc")->find();

        $customer = Db::name("customer_info")->field("buyer_name,buyer_phone")->where("id", $post['param']['customer_id'])->find();
        $tomb = Db::name("tombarea_row_col")->field("num")->where("colID", $post['param']['tomb_id'])->find();
        $pay = [
            'appid' => 'wxd5861ea6d3afeef2',
            'body' => 'sfd',
            'mch_id' => $this->mch_id,
            'nonce_str' => $this->getRand(20, true),
            'notify_url' => "http://192.168.1.106/api.php/applets/service/notify",
            'openid' => $post['param']['openid'],
            'out_trade_no' => 'JS' . date('YmdHi'),//订单编号,
            'spbill_create_ip' => '',
            'total_fee' => intval($post['param']['total_fee']),
            'trade_type' => 'JSAPI'
        ];
        $this->pay($pay);
        // 插入财务表
        $pay_ins = [
            'type' => 3,
            'itype' => 2,
            'pay_sn' => 'JS' . date('YmdHi'),//订单编号
            'tomb_id' => $post['param']['tomb_id'],
            'tomb_num' => $tomb['num'],
            'tom_price' => 0,//购墓价格
            'discount_rate' => 0,//折扣
            'deal_price' => $post['form']['total_price'],//成交
            'total_price' => $post['form']['total_price'],//应收金额
            'add_time' => time(),//备注
            'handle' => cmf_get_current_admin_id(),//收款人
            'pay_real_name' => cmf_get_current_admin_id(),//收款人
            'status' => 0,// 付款方式
//            'other_id'=> $form_id,
            'customer_id' => $post['param']['customer_id'],
        ];
        Db::name("protect_payment")->insert($post['form']);
        Db::name("order_pay_log")->insert($pay_ins);


    }

    public function expireTime()
    {
        try {
            $request = $this->request;
            $tomb_id = $request->param('tomb_id');
            $customer_id = $request->param('customer_id');
            $openId = $request->param('openId');
            $data = Db::name("order")->field("whq_end_date")->where(array("tomb_id" => $tomb_id, "customer_id" => $customer_id, "openId" => $openId))->order("add_time", "desc")->find();
            if (!empty($data)) {
                $this->success("请求成功！", $data);
            } else {
                $this->error("没有数据", $data);
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * 获取续费年限
     */
    public function renewalDuration()
    {
        $arr = array();
        for ($i = 1, $j = 0; $i < 11; $i++, $j++) {
            $arr[$j] = $i;
        }
        $this->success("请求成功", $arr);
    }

    /**
     * 获取单价标准
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getManagerCost()
    {
        $cost = Db::name("costset")->field("manager_cost")->find();
        $this->success("请求成功", $cost);
    }

    /**
     * 缴纳维护费页面
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPayMaintenanceFee()
    {
        $request = $this->request;
//        $tomb_id = $request->param("tomb_id");
//        $customer_id = $request->param("customer_id");
        $tomb_id = $request->param("tomb_id");
        $customer_id = $request->param("customer_id");
        $protectPayment = Db::name("protect_payment")->field("end_time")->where(array("mw_id" => $tomb_id, "customer_id" => $customer_id))->order("pay_time", "desc")->find();
        if (!empty($protectPayment && $protectPayment['end_time'] != null)) {
            $this->success("请求成功", $protectPayment);
        } else {
            $this->error("没有数据");
        }

    }

    //获取随机字符串
    protected function getRand($length = 6, $isAll = false)
    {

        if ($isAll) {
            $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        } else {
            $chars = '0123456789';
        }
        $randStr = '';
        for ($i = 0; $i < $length; $i++) {
            $randStr .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $randStr;
    }

    public function pay($post)
    {
//        $post['appid'] = $appid;// 小程序appid
//        $post['body'] = $body;// 商品描述
//        $post['mch_id'] = $mch_id;// 商户id
//        $post['nonce_str'] = $nonce_str; // 随机字符串，32位
//        $post['notify_url'] = $notify_url; // 回调地址
//        $post['openid'] = $openid; //用户的openid
//        $post['out_trade_no'] = $out_trade_no;// 商户订单号
//        $post['spbill_create_ip'] = $spbill_create_ip; // 支付终端的ip
//        $post['total_fee'] = $total_fee; // 单位为分
//        $post['trade_type'] = $trade_type;// 默认值JSAPI
        $sign = $this->MakeSign($post, $this->KEY); // key为商户平台设置的密钥key
        $post_xml = '<xml>
            <appid>' . $post['appid'] . '</appid>
            <body>' . $post['body'] . '</body>
            <mch_id>' . $post['mch_id'] . '</mch_id>
            <nonce_str>' . $post['nonce_str'] . '</nonce_str>
            <notify_url>' . $post['notify_url'] . '</notify_url>
            <openid>' . $post['openid'] . '</openid>
            <out_trade_no>' . $post['out_trade_no'] . '</out_trade_no>
            <spbill_create_ip>' . $post['spbill_create_ip'] . '</spbill_create_ip>
            <total_fee>' . $post['total_fee'] . '</total_fee>
            <trade_type>' . $post['trade_type'] . '</trade_type>
            <sign>' . $sign . '</sign>
            </xml>';
        // 统计微信支付接口
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $xml = $this->http_requset($url, $post_xml); // 以xml数据发往微信服务器，以获取prepay_id
        $array = $this->xmlArray($xml);
        if ($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS') {
            $time = time();
            $tmp = '';
            $tmp['appId'] = $post['appid'];
            $tmp['nonceStr'] = $post['nonce_str'];
            $tmp['package'] = 'prepay_id=' . $array['PREPAY_ID']; // 统一下单接口返回的prepay_id参数值，提交格式如 prepay_id = *
            $tmp['signType'] = 'MD5';
            $tmp['timeStamp'] = "$time";
            $data['state'] = 1;
            $data['timeStamp'] = $time;
            $data['nonceStr'] = $post['nonce_str'];
            $data['signType'] = 'MD5';
            $data['package'] = 'prepay_id=' . $array['PREPAY_ID'];
            $data['paySign'] = $this->MakeSign($tmp, $this->KEY);
            $data['out_trade_no'] = $post['out_trade_no'];
        } else {
            $data['state'] = 0;
            $data['text'] = '错误';
            $data['RETURN_CODE'] = $array['RETURN_CODE'];
            $data['RETURN_MSG'] = $array['RETURN_MSG'];
        }
        $this->success($data);
//        echo json_encode($data, JSON_UNESCAPED_UNICODE);

    }


    /**
     * 签名加密算法
     * @param $params
     * @param $KEY
     * @return string
     */
    public function MakeSign($params, $KEY)
    {

        //签名步骤- -:按字典序排序数组参数:

        ksort($params);

        $string = $this->toUrlParams($params);
        //参数进行拼接key=value&k=v↓

        // 签名步骤二:在string 后加入KEY+

        $string = $string . "&key=" . $KEY;

        //签名步骤三:MD5 JTE↓

        $string = md5($string);

        //签名步骤四:所有字符转为大写:

        $result = strtoupper($string);


        return $result;
    }

    /**
     * 将数组格式化成key=value
     * @param $params
     * @return string
     */
    public function toUrlParams($params)
        /** 将数组格式化为指定的key=value */
    {
        $string = '';
        if (!empty($params)) {
            $array = array();
            foreach ($params as $key => $value) {
                $array[] = $key . '=' . $value;
            }
            $string = implode("&", $array);
        }
        return $string;
    }

    /**
     * 以xml的格式数据为参数进行HTTPS请求
     * @param $url
     * @param null $data
     * @param array $headers
     * @return bool|string
     */
    public function http_requset($url, $data = null, $headers = array())
    {
        $info = curl_init();
        if (count($headers) >= 1) {
            curl_setopt($info, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($info, CURLOPT_URL, $url);
        curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($info, CURLOPT_POST, 1);
            curl_setopt($info, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($info, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($info);
        curl_close($info);
        return $output;
    }

    public function xmlArray($xml)
    {
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals, $index);
        xml_parser_free($p);
        $data = "";
        foreach ($index as $key => $value) {
            if ($key == 'xml' || $key == 'XML') {
                continue;
            }
            $tag = $vals[$value[0]]['tag'];
            $value = $vals[$value[0]]['value'];
            $data[$tag] = $value;
        }
        return $data;
    }


}